import { provide, inject, ref, unref } from 'vue'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { fileLogList } from '@/api/log.js'

/**
 * Symbol
 */
export const columnsSymbol = Symbol('columns')
export const dataSourceSymbol = Symbol('dataSource')
export const querySymbol = Symbol('query')
export const lineheightSymbol = Symbol('lineheight')
export const loadingSymbol = Symbol('loading')
export const filtersLogSymbol = Symbol('filtersLog')

/**
 * 注册
 */
export function useProvideContextRegistry() {
  let columns = ref([])
  let dataSource = ref([])
  let query = ref({})
  let lineheight = ref()
  let loading = ref(false)
  let filtersLog = ref()

  provide(columnsSymbol, columns)
  provide(dataSourceSymbol, dataSource)
  provide(querySymbol, query)
  provide(lineheightSymbol, lineheight)
  provide(loadingSymbol, loading)
  provide(filtersLogSymbol, filtersLog)
}

/**
 * 获取值
 */
export function useColumns() {
  return inject(columnsSymbol)
}
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useQuery() {
  return inject(querySymbol)
}
export function useLineheight() {
  return inject(lineheightSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}
export function useFiltersLog() {
  return inject(filtersLogSymbol)
}

/**
 * 管理工具
 */
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let query = useQuery()
  let loading = useLoading()
  let filtersLog = useFiltersLog()
  let operationModule = ref()
  let update = debounce(async () => {
    loading.value = true
    let { current, pageSize, dataId, ...otherQuery } = query.value
    if (filtersLog.value) {
      operationModule.value =
        filtersLog.value?.operationModule !== null
          ? filtersLog.value?.operationModule[0]
          : ''
    }
    try {
      let result = await fileLogList({
        pageIndex: current,
        pageSize,
        keyWord: otherQuery.keyWord,
        dataId,
        operationModuleKey: operationModule.value || '',
      })
      dataSource.value = result.data.records
      query.value.total = result?.data?.total || 0
      loading.value = false
    } catch (e) {
      Message.error('列表加载失败')
      loading.value = false
    }
  }, 300)

  return { update }
}
export function useQueryManager() {
  let query = useQuery()
  return {
    set(newQuery) {
      query.value = unref(newQuery)
    },
    assign(newQuery) {
      query.value = Object.assign({}, query.value, newQuery)
    },
  }
}
/**
 * 数据
 */
let ds = () =>
  Array(100)
    .fill(1)
    .map((i, index) => ({
      id: index + '',
      userId: index,
      userName: '工程师' + index,
      action: '上传',
      operationModule: 'bia',
      operationMsg: 'ddddd',
      createTime: '2025-01-12 18:34:43',
      remoteAddr: '',
      accessSuccess: '',
      accessDuration: '',
      requestIp: '',
    }))
